package com.shg.service.impl;

import com.shg.domain.LoginUser;
import com.shg.domain.ResponseResult;
import com.shg.domain.User;
import com.shg.service.LoginService;
import com.shg.utils.JwtUtil;
import com.shg.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

/**
 * @DESCRIPTION:
 * @USER: shg
 * @DATE: 2023/5/5 12:11
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;

    // 登录接口
    @Override
    public ResponseResult login(User user) {

        Authentication authentication = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());

        // 认证用户
        Authentication authenticate = authenticationManager.authenticate(authentication);

        // 如果认证没通过,抛出异常信息
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }

        // 生成token信息(使用用户id生成token,然后把这个token返回给前端)
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String id = loginUser.getUser().getId().toString();
        String token = JwtUtil.createJWT(id);
        HashMap<String, String> map = new HashMap<>();
        map.put("token", token);

        // 用户信息存入redis中
        redisCache.setCacheObject("login:"+id, loginUser);

        // 把token响应给前端
        return new ResponseResult(200, "登录成功", map);
    }

    // 退出登录接口

    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        redisCache.deleteObject("login:"+userId);
        return new ResponseResult(200, "退出成功");
    }
}
